// ChatInput.vue created successfully

<template>
  <view class="chat-footer" :class="{ 'expanded-view': isExpandedView, 'recording-active': isRecording }" :style="{ bottom: keyboardHeight + 'px' }">
    <!-- 添加滑动按钮区域，在输入框上方 -->
    <view class="slider-buttons-area" v-if="!inputMessage.trim() && !isExpandedView">
      <scroll-view class="slider-scroll" scroll-x="true">
        <view class="slider-buttons">
          <view class="slider-button" @tap="handleQuickAction('planning')">
            <text>大理有啥玩</text>
          </view>
          <view class="slider-button" @tap="handleQuickAction('photo')">
            <text>大理有啥吃</text>
          </view>
          <view class="slider-button" @tap="handleQuickAction('spot')">
            <text>大理民宿</text>
          </view>
        </view>
      </scroll-view>
    </view>
  
    <!-- 普通输入视图 -->
    <view class="input-area" v-if="!isExpandedView" :class="{'recording': isRecording}">
      <!-- 相机图标 - 已隐藏 -->
      <!-- 原相机图标代码
      <view class="camera-icon" @tap="chooseImage" v-if="!inputMessage.trim() && inputMode === 'text'">
        <image src="/static/images/doubao_icon/Camera.png" mode="aspectFit" class="input-icon"></image>
      </view>
      -->
      
      <!-- 文本输入模式 -->
      <view class="input-wrapper" v-if="inputMode === 'text'" 
            :class="{
              'expanded-input': inputMessage.trim(),
              'with-voice-button': !inputMessage.trim() // 只在没有输入内容时添加语音按钮的间距
            }">
        <textarea 
          class="message-input" 
          placeholder="发消息..." 
          v-model="inputMessage"
          :maxlength="-1"
          :auto-height="true"
          :show-confirm-bar="false"
          @input="handleTextareaInput"
          @focus="handleTextareaFocus"
          @blur="handleTextareaBlur"
          @confirm="sendMessage"
          :style="{ height: textareaHeight + 'px', paddingRight: textLines >= 3 ? '40px' : '8px' }"
          ref="textarea"
        ></textarea>
        <!-- 放大按钮条件：只保留文本超过三行 -->
        <view v-if="textLines >= 3" class="expand-icon top-right" @tap="expandTextView">
          <image src="/static/images/doubao_icon/moreBig.png" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- 语音输入模式 -->
      <view class="voice-input-wrapper" v-else>
        <view 
          class="voice-button"
          @touchstart="startRecording"
          @touchend="stopRecording"
          @touchcancel="cancelRecording"
          @touchmove="handleTouchMove"
        >
          按住说话
        </view>
      </view>
      
      <!-- 操作图标 -->
      <view class="action-icons">
        <!-- 语音/键盘切换图标 - 只在没有输入内容时显示 -->
        <view class="action-icon voice-icon" @tap="toggleInputMode" v-if="!inputMessage.trim()">
          <image 
            :src="inputMode === 'text' ? '/static/images/doubao_icon/voice.png' : '/static/images/doubao_icon/keyborad.png'" 
            mode="aspectFit" 
            class="input-icon"
          ></image>
        </view>
        
        <!-- 加号/发送按钮 -->
        <view class="action-icon send-icon" v-if="inputMode === 'text'">
          <image 
            @tap="inputMessage.trim() ? sendMessage() : toggleFunctionButtons()"
            :src="inputMessage.trim() 
              ? '/static/images/doubao_icon/send_message.png' 
              : (moreButtonActive ? '/static/images/doubao_icon/more_ing.png' : '/static/images/doubao_icon/more.png')" 
            mode="aspectFit" 
            class="input-icon"
          ></image>
        </view>
        
        <!-- 语音模式下的加号按钮 -->
        <view class="action-icon send-icon" v-else>
          <image 
            @tap="toggleFunctionButtons"
            :src="moreButtonActive ? '/static/images/doubao_icon/more_ing.png' : '/static/images/doubao_icon/more.png'" 
            mode="aspectFit" 
            class="input-icon"
          ></image>
        </view>
      </view>
    </view>
    
    <!-- 扩展输入区域 -->
    <view v-if="isExpandedView" class="input-expanded-overlay">
      <!-- 半透明顶部区域 -->
      <view class="expanded-header-overlay" @tap="closeExpandedView"></view>
      
      <!-- 扩展输入区域 -->
      <view class="expanded-input-area" :style="{ paddingBottom: `${safeAreaBottom}px` }">
        <view class="expanded-header">
          <view class="title">编辑</view>
          <view class="shrink-icon-expanded" @tap="closeExpandedView">
            <image src="/static/images/doubao_icon/dropBack.png" mode="aspectFit"></image>
          </view>
        </view>
        
        <textarea 
          class="expanded-textarea" 
          v-model="inputMessage"
          :cursor-spacing="20"
          :show-confirm-bar="false"
          :maxlength="-1"
          :adjust-position="false"
          focus
          @input="handleTextareaInput"
        ></textarea>
        
        <!-- 发送按钮 -->
        <view class="send-expanded-button" @tap="sendMessage" v-if="inputMessage.trim()">
          <image src="/static/images/doubao_icon/send_message.png" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    
    <!-- 录音状态遮罩层 -->
    <view class="recording-overlay" v-if="isRecording">
      <!-- 提示文本容器 -->
      <view class="recording-tip-container">
        <view class="recording-tip" :class="{'cancel-tip': isCancelling}">
          <text>{{ isCancelling ? '松手取消' : '松手发送，上移取消' }}</text>
        </view>
      </view>
      
      <!-- 波形区域 -->
      <view class="recording-wave-area" :class="{'cancel-state': isCancelling}">
        <view class="recording-wave-dots">
          <view v-for="(dot, index) in 70" :key="index" class="wave-dot" :class="{'wave-dot-active': index === activeWaveDot}"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ChatInput',
  props: {
    // 接收父组件传递的底部安全区域高度
    safeAreaBottom: {
      type: Number,
      default: 0
    },
    keyboardHeight: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      inputMessage: '',
      inputMode: 'text', // 'text' 或 'voice'
      moreButtonActive: false,
      textareaHeight: 28, // 文本区域默认高度
      isExpandedView: false, // 是否展开大视图
      textLines: 1, // 文本行数，默认为1行
      isRecording: false,
      isCancelling: false,
      touchStartY: 0,
      activeWaveDot: 20, // 当前激活的波形点
      waveDotInterval: null,
    }
  },
  watch: {
    // 监视所有可能影响高度的属性
    textareaHeight() {
      this.updateHeight();
    },
    isExpandedView() {
      this.updateHeight();
    },
    inputMessage(newVal) {
      // 切换滑块按钮时
      if (!newVal.trim()) {
        this.updateHeight();
      }
    },
    isRecording(){
      this.updateHeight();
    }
  },
  mounted() {
    this.updateHeight();
  },
  methods: {
    updateHeight() {
      this.$nextTick(() => {
        uni.createSelectorQuery().in(this).select('.chat-footer').boundingClientRect(rect => {
          if (rect) {
            this.$emit('height-change', rect.height);
          }
        }).exec();
      });
    },
    // 发送消息
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      // 发送消息到父组件
      this.$emit('send-message', this.inputMessage.trim());
      
      // 清空输入框
      this.inputMessage = '';
      
      // 重置输入状态
      this.resetInputState();
      
      // 关闭扩展视图
      this.isExpandedView = false;
    },
    
    // 处理快捷操作按钮点击
    handleQuickAction(action) {
      this.$emit('quick-action', action);
    },
    
    // 选择图片
    chooseImage() {
      this.$emit('choose-image');
    },
    
    // 切换输入模式（文本/语音）
    toggleInputMode() {
      this.inputMode = this.inputMode === 'text' ? 'voice' : 'text';
    },
    
    // 切换功能按钮显示
    toggleFunctionButtons() {
      this.moreButtonActive = !this.moreButtonActive;
      this.$emit('toggle-function-buttons', this.moreButtonActive);
    },
    
    // 处理文本输入事件
    handleTextareaInput(e) {
      // 获取输入事件的值
      if (typeof e === 'object' && e.detail) {
        const text = e.detail.value || '';
        
        // 计算文本行数
        let lines = 1;
        
        // 计算换行符数量
        const newLineCount = (text.match(/\n/g) || []).length;
        
        // 计算每行平均字符数
        const avgCharsPerLine = 20; // 假设平均每行20个字符
        const textWithoutNewlines = text.replace(/\n/g, '');
        const charsLineCount = Math.ceil(textWithoutNewlines.length / avgCharsPerLine);
        
        // 总行数是换行符数量+1与字符行数的最大值
        lines = Math.max(newLineCount + 1, charsLineCount);
        this.textLines = Math.max(1, Math.min(lines, 5)); // 行数范围在1-5之间
        
        // 根据行数调整文本框高度
        const lineHeight = 20; // 每行高度约为20px
        const baseHeight = 28; // 基础高度
        const calculatedHeight = baseHeight + ((this.textLines - 1) * lineHeight);
        this.textareaHeight = calculatedHeight;
        
        // 如果文本被清空，重置状态
        if (!text.trim()) {
          this.resetInputState();
        }
      }
    },
    
    // 重置输入状态
    resetInputState() {
      this.textareaHeight = 28; // 重置高度到基础高度
      this.textLines = 1; // 重置行数
      this.moreButtonActive = false; // 重置加号按钮状态
      
      // 确保立即应用样式更新
      this.$nextTick(() => {
        if (this.$refs.textarea) {
          this.$refs.textarea.style.height = '28px';
        }
      });
    },
    
    // 处理输入框获取焦点
    handleTextareaFocus() {
      // 输入框获取焦点时隐藏功能按钮
      this.moreButtonActive = false;
      this.$emit('input-focus');
    },
    
    // 处理输入框失去焦点
    handleTextareaBlur() {
      // 如果输入框为空，重置到初始状态
      if (!this.inputMessage.trim()) {
        this.resetInputState();
      }
      this.$emit('input-blur');
    },
    
    // 展开大视图文本编辑器
    expandTextView() {
      this.isExpandedView = true;
    },
    
    // 关闭大视图
    closeExpandedView() {
      this.isExpandedView = false;
    },
    
    // 开始录音
    startRecording() {
      this.isRecording = true;
      this.touchStartY = 0;
      this.isCancelling = false;
      
      // 启动波形动画
      this.startWaveAnimation();
      
      // 震动反馈
      uni.vibrateShort();
      
      // 发送事件到父组件
      this.$emit('start-recording');
    },
    
    // 停止录音
    stopRecording() {
      if (this.isCancelling) {
        this.cancelRecording();
        return;
      }
      
      this.isRecording = false;
      this.stopWaveAnimation();
      
      // 发送事件到父组件
      this.$emit('stop-recording');
    },
    
    // 取消录音
    cancelRecording() {
      this.isRecording = false;
      this.stopWaveAnimation();
      
      // 发送事件到父组件
      this.$emit('cancel-recording');
    },
    
    // 处理手指移动事件
    handleTouchMove(e) {
      if (!this.isRecording) return;
      
      if (!this.touchStartY) {
        this.touchStartY = e.touches[0].clientY;
      }
      
      const moveY = e.touches[0].clientY;
      const diffY = this.touchStartY - moveY;
      
      // 上滑超过50像素则切换到取消状态
      if (diffY > 50) {
        if (!this.isCancelling) {
          this.isCancelling = true;
          // 震动提示
          uni.vibrateShort();
        }
      } else {
        if (this.isCancelling) {
          // 从取消状态恢复到录音状态时也添加震动反馈
          uni.vibrateShort();
        }
        this.isCancelling = false;
      }
    },
    
    // 启动波形动画
    startWaveAnimation() {
      // 清除可能存在的定时器
      this.stopWaveAnimation();
      
      // 创建新的定时器，模拟波形动画
      this.waveDotInterval = setInterval(() => {
        // 随机选择几个点高亮
        this.activeWaveDot = Math.floor(Math.random() * 70);
      }, 100);
    },
    
    // 停止波形动画
    stopWaveAnimation() {
      if (this.waveDotInterval) {
        clearInterval(this.waveDotInterval);
        this.waveDotInterval = null;
      }
    }
  }
}
</script>

<style lang="scss">
.chat-footer {
  background-color: #ffffff;
  padding: 8px 0;
  border-top: none;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
  padding-bottom: calc(8px + env(safe-area-inset-bottom));
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  transition: bottom 0.2s ease-out;
  
  &.expanded-view {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    padding: 0;
    z-index: 999;
  }
  
  &.recording-active {
    .slider-buttons-area {
      display: none !important; // 确保在录音状态下完全隐藏滑动按钮区域
    }
  }
  
  .slider-buttons-area {
    padding: 5px 0;
    background-color: #ffffff;
    border-bottom: none;
    margin-bottom: 5px;
  }
  
  .slider-scroll {
    width: 100%;
    white-space: nowrap;
    padding: 0 16px;
    
    &::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }
  }
  
  .slider-buttons {
    display: inline-flex;
    padding: 5px 0;
  }
  
  .slider-button {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 8px 16px;
    margin-right: 12px;
    background-color: #f5f5f5;
    border-radius: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    image {
      width: 18px;
      height: 18px;
      margin-right: 6px;
    }
    
    text {
      font-size: 14px;
      color: #333;
      white-space: nowrap;
    }
    
    &:active {
      background-color: #eaeaea;
    }
  }
  
  .input-area {
    display: flex;
    align-items: flex-start;
    background-color: #f5f5f5;
    border-radius: 20px;
    padding: 8px 12px;
    margin: 0 16px;
    box-shadow: 0 3px 15px rgba(0, 0, 0, 0.1), 0 1px 5px rgba(0, 0, 0, 0.08);
    position: relative;
    min-height: 28px;
    transition: all 0.3s ease;
    
    .camera-icon {
      margin-right: 10px;
      display: flex;
      align-items: center;
      align-self: flex-end;
      margin-bottom: 8px;
      
      .input-icon {
        width: 24px;
        height: 24px;
        opacity: 0.8;
      }
    }
    
    .input-wrapper {
      flex: 1;
      position: relative;
      transition: all 0.3s ease;
      padding-right: 40px;
      
      &.with-voice-button {
        padding-right: 70px;
      }
      
      &.expanded-input {
        margin-left: 0;
      }
      
      .message-input {
        width: 100%;
        min-height: 28px;
        max-height: 100px;
        font-size: 15px;
        background-color: transparent;
        color: #333;
        padding: 8px 0;
        line-height: 1.4;
        box-sizing: border-box;
        transition: all 0.3s ease;
      }
      
      .expand-icon {
        position: absolute;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1;
        transition: opacity 0.3s ease;
        
        &.top-right {
          right: 8px;
          top: 2px;
        }
        
        image {
          width: 20px;
          height: 20px;
          opacity: 0.7;
        }
      }
    }
    
    .voice-input-wrapper {
      flex: 1;
      display: flex;
      align-items: center;
      padding: 0 16px;
      
      .voice-button {
        width: 100%;
        height: 36px;
        line-height: 36px;
        text-align: center;
        color: #666;
        font-size: 15px;
        background-color: #f5f5f5;
        border-radius: 18px;
        box-shadow: none;
        
        &:active {
          background-color: #e0e0e0;
          color: #0078ff;
        }
      }
    }
    
    .action-icons {
      position: absolute; 
      right: 12px;
      bottom: 15px;
      display: flex;
      align-items: center;
      z-index: 5;
      
      .action-icon {
        padding: 0 4px;
        display: flex;
        align-items: center;
        
        &.voice-icon {
          margin-right: 8px;
        }
        
        .input-icon {
          width: 24px;
          height: 24px;
          opacity: 0.9;
          transition: all 0.3s ease;
        }
      }
    }
  }
  
  .input-expanded-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    display: flex;
    flex-direction: column;
    
    .expanded-header-overlay {
      flex: 0.4;
      background-color: rgba(0, 0, 0, 0.2);
    }
    
    .expanded-input-area {
      flex: 0.6;
      background-color: #fff;
      border-radius: 20px 20px 0 0;
      overflow: hidden;
      position: relative;
      display: flex;
      flex-direction: column;
      box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
      
      .expanded-header {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 16px;
        position: relative;
        border-bottom: 1px solid #f0f0f0;
        
        .title {
          font-size: 16px;
          font-weight: 500;
        }
        
        .shrink-icon-expanded {
          position: absolute;
          right: 16px;
          top: 50%;
          transform: translateY(-50%);
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          image {
            width: 18px;
            height: 18px;
          }
        }
      }
      
      .expanded-textarea {
        flex: 1;
        width: 100%;
        font-size: 16px;
        line-height: 24px;
        padding: 16px 16px 60px 16px;
        box-sizing: border-box;
        border: none;
      }
      
      .send-expanded-button {
        position: absolute;
        right: 16px;
        bottom: 16px;
        width: 40px;
        height: 40px;
        border-radius: 20px;
        background-color: #f5f2f2;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        z-index: 10;
        
        image {
          width: 18px;
          height: 18px;
        }
      }
    }
  }
}

// 录音状态遮罩层样式
.recording-overlay {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: transparent;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  z-index: 10001;
  
  .recording-tip-container {
    position: absolute;
    bottom: calc(44px + 16px + env(safe-area-inset-bottom));
    left: 0;
    right: 0;
    height: 120px;
    background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.8) 30%, rgba(255,255,255,1) 60%, rgba(255,255,255,1) 100%);
    z-index: 10002;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    padding-bottom: 15px;
  }
  
  .recording-tip {
    text-align: center;
    
    text {
      display: inline-block;
      color: #333333;
      font-size: 14px;
      padding: 8px 16px;
      background-color: #ffffff;
      border-radius: 16px;
      white-space: nowrap;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    
    &.cancel-tip text {
      color: #ff453a;
    }
  }
  
  .recording-wave-area {
    width: calc(100% - 32px);
    margin: 0 16px;
    height: 44px;
    background-color: #0066ff;
    border-radius: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    position: relative;
    box-shadow: 0 3px 15px rgba(0, 0, 0, 0.1), 0 1px 5px rgba(0, 0, 0, 0.08);
    margin-bottom: calc(8px + env(safe-area-inset-bottom));
    padding: 0;
    box-sizing: border-box;
    transition: all 0.3s ease;
    
    &.cancel-state {
      background-color: #ff453a;
    }
    
    .recording-wave-dots {
      width: 90%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 100%;
      
      .wave-dot {
        width: 1.5px;
        height: 5px;
        background-color: #fff;
        border-radius: 0px;
        transition: height 0.15s ease;
        
        &.wave-dot-active {
          height: 8px;
        }
      }
    }
  }
}

// 确保录音状态下隐藏其他按钮
.input-area.recording {
  opacity: 0;
  pointer-events: none;
}
</style>
